﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using Confucius.entity;
using Confucius.dao;
using System.IO.IsolatedStorage;
using Confucius.utils;
using Confucius.daoImpl;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;

namespace Confucius.pages
{
    public partial class NPCTalkingPage : PhoneApplicationPage
    {
        private string npcID;
        private string dialogNodeID;
        private string gameID;
        private DialogNode currentDialogNode;
        private List<DialogNodeOrder> currentDialogNodeOrders;
        private NPCDAO npcDAO;

        public NPCTalkingPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (this.NavigationContext.QueryString.ContainsKey("npcID"))
            {
                npcID = NavigationContext.QueryString["npcID"];
            }
            if (this.NavigationContext.QueryString.ContainsKey("startDialogNodeID"))
            {
                dialogNodeID = NavigationContext.QueryString["startDialogNodeID"];
            }

            if (npcID != null && dialogNodeID != null)
            {
                IsolatedStorageSettings.ApplicationSettings.Remove(Constants.CURRENT_TALKING_NPCID);
                IsolatedStorageSettings.ApplicationSettings.Remove(Constants.CURRENT_DIALOGNODEID);
                IsolatedStorageSettings.ApplicationSettings.Add(Constants.CURRENT_TALKING_NPCID, npcID);
                IsolatedStorageSettings.ApplicationSettings.Add(Constants.CURRENT_DIALOGNODEID, dialogNodeID);
                IsolatedStorageSettings.ApplicationSettings.Save();
            }

            npcID = "";
            dialogNodeID = "";
            gameID = "";
            if (IsolatedStorageSettings.ApplicationSettings.Contains(Constants.CURRENT_TALKING_NPCID))
            {
                npcID = (string)IsolatedStorageSettings.ApplicationSettings[Constants.CURRENT_TALKING_NPCID];
            }

            if (IsolatedStorageSettings.ApplicationSettings.Contains(Constants.CURRENT_DIALOGNODEID))
            {
                dialogNodeID = (string)IsolatedStorageSettings.ApplicationSettings[Constants.CURRENT_DIALOGNODEID];
            }
            if (IsolatedStorageSettings.ApplicationSettings.Contains(Constants.CURRENT_GAMEID))
            {
                gameID = (string)IsolatedStorageSettings.ApplicationSettings[Constants.CURRENT_GAMEID];
            }

            npcDAO = new NPCDAOImpl();
            NPC npc = npcDAO.readNPC(npcID, gameID);

            // Update the UI npcNameInTalking
            npcNameInTalking.Text = npc.Name;

            // Update the UI npcFigure
            //Uri uri = new Uri("/" + Constants.ASSEMBLY_NAME_CONFUCIUS + ";component/assets/gameFiles/"
            //    + gameID + "/" + npc.FigureID + ".png", UriKind.Relative);
            createMedia(gameID, npc);


            // update nodes
            currentDialogNode = npcDAO.readDialogNode(dialogNodeID, gameID);
            currentDialogNodeOrders = npcDAO.retrieveAdjacentDialogNodeOrder(
                    currentDialogNode.DialogNodeID, gameID);

            updateTalkingUI();
        }

        private void createMedia(string gameID, NPC npc)
        {
            string figureMedia = npc.FigureID;
            string[] mediaString = figureMedia.Split('.');
            if (mediaString.Length > 0)
            {
                if (mediaString.Length > 1)
                {
                    if (mediaString[1].Equals("png"))
                    {
                        PlayButton.Visibility = Visibility.Collapsed;
                        Uri uri = ConfuciusUtil.buildImageUri(gameID, mediaString[0]);
                        npcFigure.Source = new BitmapImage(uri);
                    }
                    else if (mediaString[1].Equals("wmv") || mediaString[1].Equals("mp4") ||
                        mediaString[1].Equals("mp3"))
                    {
                        PlayButton.Visibility = Visibility.Visible;
                        Uri uri = ConfuciusUtil.buildVideoBackgroundUri(Constants.DIALOG_MEDIA_BACKGROUND);
                        npcFigure.Source = new BitmapImage(uri);

                    }
                }
                else
                {
                    // Cater for old version
                    Uri uri = ConfuciusUtil.buildImageUri(gameID, mediaString[0]);
                    npcFigure.Source = new BitmapImage(uri);
                }


            }
        }

        private void talkNextBtn_Click(object sender, RoutedEventArgs e)
        {
            if (currentDialogNode.NodeType.Equals(
                        DialogNode.PROGRESS_TYPE))
            {
                if (currentDialogNodeOrders.Count == 0)
                {
                    MessageBox.Show("Nothing finish after the chat", "Message", MessageBoxButton.OK);
                    NavigationService.GoBack();
                }
                else
                {
                    if (currentDialogNode.InteractionType.Equals(
                            DialogNode.ANSWER_INTERACT))
                    {
                        String answer = answerTextView.Text;
                        if (answer.Length != 0)
                        {
                            if (currentDialogNodeOrders[0].Answer.Length == 0 || answer.Equals(currentDialogNodeOrders[0].Answer))
                            {
                                answerTextView.Visibility = Visibility.Collapsed;
                                currentDialogNode = npcDAO.readDialogNode(
                                        currentDialogNodeOrders[0].ToNodeID, gameID);
                                currentDialogNodeOrders = npcDAO
                                        .retrieveAdjacentDialogNodeOrder(
                                                currentDialogNode.DialogNodeID, gameID);
                                updateTalkingUI();
                            }
                            else
                            {
                                MessageBox.Show("Wrong answer. Please try again.", "Message",
                                    MessageBoxButton.OK);
                                //NavigationService.GoBack();
                            }
                        }
                        else
                        {
                            MessageBox.Show("Please enter an answer!", "Message",
                                    MessageBoxButton.OK);
                        }
                    }
                    else if (currentDialogNode.InteractionType.Equals(DialogNode.BRANCH_INTERACT))
                    {
                        int selectedIndex = -1;

                        for (int i = 0; i < currentDialogNodeOrders.Count; i++)
                        {
                            ((RadioButton)listBox.Items[i]).Visibility = Visibility.Collapsed;
                            if ((bool)((RadioButton)listBox.Items[i]).IsChecked)
                            {
                                selectedIndex = i;
                            }
                        }

                        if (selectedIndex == -1)
                        {
                            MessageBox.Show("Please select an answer!", "Message",
                                    MessageBoxButton.OK);
                            updateTalkingUI();
                        }
                        else
                        {
                            currentDialogNode = npcDAO.readDialogNode(
                                        currentDialogNodeOrders[selectedIndex].ToNodeID, gameID);
                            currentDialogNodeOrders = npcDAO.retrieveAdjacentDialogNodeOrder(
                                    currentDialogNode.DialogNodeID, gameID);
                            updateTalkingUI();
                        }
                    }
                    else if (currentDialogNode.InteractionType
                            .Equals(DialogNode.DISPLAY_INTERACT))
                    {
                        currentDialogNode = npcDAO.readDialogNode(
                                currentDialogNodeOrders[0].ToNodeID, gameID);
                        currentDialogNodeOrders = npcDAO.retrieveAdjacentDialogNodeOrder(
                                currentDialogNode.DialogNodeID, gameID);
                        updateTalkingUI();
                    }

                }
            }
            else if (currentDialogNode.NodeType.Equals(
                        DialogNode.FINISH_TYPE))
            {
                MessageBox.Show("You finished the chat.", "Message",
                                    MessageBoxButton.OK);
                NavigationService.GoBack();

            }
        }

        private void updateTalkingUI()
        {
            npcDisplayTextInTalking.Text = currentDialogNode.DisplayText;

            if (currentDialogNode.NodeType.Equals(DialogNode.PROGRESS_TYPE))
            {
                if (currentDialogNodeOrders.Count == 0)
                {
                    talkNextBtn.Content = Constants.LEAVE_TALK;
                }
                else
                {
                    talkNextBtn.Content = Constants.NEXT_TALK;

                    if (currentDialogNode.InteractionType.Equals(
                            DialogNode.ANSWER_INTERACT))
                    {
                        answerTextView.Visibility = Visibility.Visible;
                    }
                    else if (currentDialogNode.InteractionType.Equals(
                            DialogNode.BRANCH_INTERACT))
                    {
                        for (int i = 0; i < currentDialogNodeOrders.Count; i++)
                        {
                            DialogNodeOrder order = currentDialogNodeOrders.ElementAt(i);
                            if (!order.Answer.Equals("null"))
                            {
                                ((RadioButton)listBox.Items[i]).Content = order.Answer;
                                ((RadioButton)listBox.Items[i]).Visibility = Visibility.Visible;
                            }
                        }
                    }

                }
            }
            else if (currentDialogNode.NodeType.Equals(
                DialogNode.FINISH_TYPE))
            {
                talkNextBtn.Content = Constants.FINISH_TALK;
                npcDAO.updateNPCStatus(npcID, NPC.END_CHAT);
                // update gamerule
                GameRuleManager.getInstance(gameID).gameRuleCheck(
                        npcID, Condition.FINISH_CHAT_CONDITION);
            }
        }

        private void MediaClickDown(object sender, RoutedEventArgs e)
        {
            string npcIDString = "";
            string currentGameID = "";
            if (IsolatedStorageSettings.ApplicationSettings.Contains(Constants.CURRENT_TALKING_NPCID))
            {
                npcIDString = (string)IsolatedStorageSettings.ApplicationSettings[Constants.CURRENT_TALKING_NPCID];
            }
            if (IsolatedStorageSettings.ApplicationSettings.Contains(Constants.CURRENT_GAMEID))
            {
                currentGameID = (string)IsolatedStorageSettings.ApplicationSettings[Constants.CURRENT_GAMEID];
            }

            if (npcIDString == "" || currentGameID == "")
            {
                return;
            }
            else
            {
                NPC npc = new NPCDAOImpl().readNPC(npcIDString, currentGameID);
                string figureMedia = npc.FigureID;
                string[] mediaString = figureMedia.Split('.');
                if (mediaString.Length > 1)
                {
                    if (mediaString[1].Equals("wmv") || mediaString[1].Equals("mp4") ||
                        mediaString[1].Equals("mp3"))
                    {
                        Uri imageSource = new Uri("/Confucius;component/assets/ui/PlayPressed.png", UriKind.Relative);
                        PlayButton.Source = new BitmapImage(imageSource);
                        PlayButton.Visibility = Visibility.Visible;
                        Uri uri = ConfuciusUtil.buildMediaUri(currentGameID, npc.FigureID);
                        MediaPlayerLauncher mediaPlayerLauncher = new MediaPlayerLauncher();
                        mediaPlayerLauncher.Location = MediaLocationType.Install;
                        mediaPlayerLauncher.Media = uri;

                        mediaPlayerLauncher.Show();

                    }

                }
            }
        }

        private void MediaClickUp(object sender, RoutedEventArgs e)
        {
            string npcIDString = "";
            string currentGameID = "";
            if (IsolatedStorageSettings.ApplicationSettings.Contains(Constants.CURRENT_TALKING_NPCID))
            {
                npcIDString = (string)IsolatedStorageSettings.ApplicationSettings[Constants.CURRENT_TALKING_NPCID];
            }
            if (IsolatedStorageSettings.ApplicationSettings.Contains(Constants.CURRENT_GAMEID))
            {
                currentGameID = (string)IsolatedStorageSettings.ApplicationSettings[Constants.CURRENT_GAMEID];
            }

            if (npcIDString == "" || currentGameID == "")
            {
                return;
            }
            else
            {
                NPC npc = new NPCDAOImpl().readNPC(npcIDString, currentGameID);
                string figureMedia = npc.FigureID;
                string[] mediaString = figureMedia.Split('.');
                if (mediaString.Length > 1)
                {
                    if (mediaString[1].Equals("wmv") || mediaString[1].Equals("mp4") ||
                        mediaString[1].Equals("mp3"))
                    {
                        Uri imageSource = new Uri("/Confucius;component/assets/ui/PlayNormal.png", UriKind.Relative);
                        PlayButton.Source = new BitmapImage(imageSource);
                        PlayButton.Visibility = Visibility.Visible;

                    }

                }
            }
        }
    }
}